import { memo, ForwardRefRenderFunction, useState, useEffect } from 'react'
import { downloadFile, getFileInfoByIds } from '@/api/file'
import { FileTextOutlined, DownloadOutlined, DeleteOutlined } from '@ant-design/icons'
interface Props {
  delect: (e: any) => void
  ids: Array<any>
  keys?: string
  edit?: boolean
}

const ResolveFileList: ForwardRefRenderFunction<unknown, Props> = (props: Props) => {
  const [FileList, setFileList] = useState<any[]>([])
  const handleDelect = (index: any, id: any) => {
    setFileList(FileList.filter((item, idx) => idx !== index))
    props.delect({ value: id })
  }

  const handleDownloadFile = (id: any) => {
    downloadFile({
      file_id: id
    })
  }

  const getFileMessage = (ids: any) => {
    if (!ids?.length) {
      setFileList([])
      return
    }
    getFileInfoByIds({ ids: ids.map((item: any) => Number(item)) }).then((res: any) => {
      setFileList(res)
    })
  }

  useEffect(() => getFileMessage(props.ids), [props.ids])
  return (
    <div>
      {FileList.map((item, index) => (
        <div key={index} className="flex">
          <FileTextOutlined />
          <div style={{ margin: '0 10px' }}>{item.name}</div>
          <DownloadOutlined style={{ marginRight: '5px' }} onClick={() => handleDownloadFile(item.id)} />
          {props.edit ? <DeleteOutlined onClick={() => handleDelect(index, item.id)} /> : null}
        </div>
      ))}
    </div>
  )
}
export default memo(ResolveFileList)
